<template lang="html">
  <div class="main">
    <div class="videomain">
     <video id="video" autoplay></video>
   </div>
   <button id="capture">拍照</button>
   <canvas id="canvas" width="2000" height="2000"></canvas>
  </div>
</template>

<script>
export default {
  data () {
    return {
      video: null
    };
  },
  methods: {
    ok () {

    },
    getUserMedia (constraints, success, error) {
      if (navigator.mediaDevices.getUserMedia) {
        // 最新的标准API
        navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
      } else if (navigator.webkitGetUserMedia) {
        // webkit核心浏览器
        navigator.webkitGetUserMedia(constraints, success, error);
      } else if (navigator.mozGetUserMedia) {
        // firfox浏览器
        navigator.mozGetUserMedia(constraints, success, error);
      } else if (navigator.getUserMedia) {
      // 旧版API
        navigator.getUserMedia(constraints, success, error);
      }
    },
    success (stream) {
      // 兼容webkit核心浏览器
      let CompatibleURL = window.URL || window.webkitURL;
      // 将视频流设置为video元素的源
      console.log(stream, CompatibleURL);
      // this.video.src = CompatibleURL.createObjectURL(stream);
      this.video.srcObject = stream;
      this.video.play();
    },
    error (error) {
      console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
    }
  },
  mounted () {
    this.video = document.getElementById('video');
    setTimeout(() => {
      if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
        // 调用用户媒体设备, 访问摄像头
        this.getUserMedia({video: true}, this.success, this.error);
      } else {
        alert('不支持访问用户媒体');
      }
      let canvas = document.getElementById('canvas');
      let context = canvas.getContext('2d');
      document.getElementById('capture').addEventListener('click', () => {
        context.drawImage(this.video, 0, 0, 2000, 2000);
      });
    }, 1000);
  }
};
</script>

<style lang="css">
.main {
  position: relative;
  width: 400px;
  height: 400px;
}
.videomain{
  width: 400px;
  height: 400px;
}
.videomain video {
  /*修复尺寸*/
  width: 100%;
  height: 100%;
  max-height: 100%;
}
#capture {
  position: absolute;
  bottom: 10px;
  left: 200px;
}
#canvas {
  width: 200px;
  height: 200px;
  position: absolute;
  top: 0px;
  right: 0px;
}
</style>
